﻿using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Reflection.Emit;
using System.Reflection.Metadata;

namespace Sample.JwtBearer.Api.Data;

public class AppJwtBearerDbContext : IdentityDbContext<AppUser, IdentityRole<string>, string>
{
    public DbSet<RefreshToken> RefreshTokens { get; set; }

    public AppJwtBearerDbContext(DbContextOptions<AppJwtBearerDbContext> options) : base(options)
    {
    }

    /// <summary>
    /// 数据库上下文配置函数
    /// </summary>
    /// <param name="optionsBuilder"></param>
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
    }

    /// <summary>
    /// 描述各个实体类之间的关系和实体内部的设置
    /// </summary>
    /// <param name="builder"></param>
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        // 指定模型
        builder.Entity<AppUser>(b => { b.ToTable("AppUsers"); });

        // 添加伪主键
        builder.Entity<AppUser>().HasKey(x => new { x.Id });
        builder.Entity<AppUser>().Property(e => e.Id).ValueGeneratedOnAdd();

        builder.Entity<IdentityUserClaim<string>>(b => { b.ToTable("AppUserClaims"); });

        builder.Entity<IdentityUserLogin<string>>(b => { b.ToTable("AppUserLogins"); });

        builder.Entity<IdentityUserToken<string>>(b => { b.ToTable("AppUserTokens"); });

        builder.Entity<IdentityRole<string>>(b => { b.ToTable("AppRoles"); });

        builder.Entity<IdentityRoleClaim<string>>(b => { b.ToTable("AppRoleClaims"); });

        builder.Entity<IdentityUserRole<string>>(b => { b.ToTable("AppUserRoles"); });
    }
}